/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bookstore.mvc.controller;

import bookstore.bean.LoginBean;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.File;
import java.util.List;
import java.util.Iterator;
import javax.servlet.ServletContext;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import bookstore.jaxb.Books;
import bookstore.jaxb.Books.Book;
import bookstore.util.Utilities;
import bookstore.validator.JAXBBookStoreValidationHandler;
import java.util.ArrayList;

import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;

/**
 *
 * @author HongDC
 */
public class AdminController extends HttpServlet {

    private String uploadPath = "";
    private String booksSchemaPath = "";
    private File file;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        uploadPath = getServletContext().getRealPath("/") + "upload/";
        booksSchemaPath = getServletContext().getRealPath("/") + "schemas/OrderSchema.xml";
        String action = request.getParameter("action");
        HttpSession session = request.getSession(true);
        String errorMessage = "";
        boolean authorized = false;
        if (session.getAttribute("USER") != null) {
            LoginBean user = (LoginBean) session.getAttribute("USER");
            if (user.getType().equals("Admin")) {
                authorized = true;
            }
        }
        if (authorized) {
            if (action.equals("Upload")) {
                // process upload
                file = uploadFile(uploadPath, request);
                Books books = (Books) Utilities.customUnMarshall(booksSchemaPath, file, response, true);
                //Error while parsing
                if (books == null) {
                    //request.getRequestDispatcher("error.jsp").forward(request, response);
                    
                } else {
                    int count = insertBook(books.getBook());

                    //            insertBook(books.getBook());
                    if (count == books.getBook().size()) {
                        Utilities.createResponseMessage(response.getWriter(), count + " titles have been imported.", "OK");
                    } else {
                        Utilities.createResponseMessage(response.getWriter(), "Import failed.\nPlease check your XML file.", "NG");
                    }
                }


            }
        } else {
            Utilities.createResponseMessage(response.getWriter(), "Authorization failed.\nPlease check your role again.", "NG");
        }
        out.close();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private File uploadFile(String filePath, HttpServletRequest request) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(100 * 1024); // set maxium file size of 100KBFile file = null;
        File f = null;
        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();
            if (i.hasNext()) {
                FileItem item = (FileItem) i.next();
                if (!item.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    // Write the file

                    if (fileName.lastIndexOf("\\") >= 0) {
                        f = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        f = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }
                    item.write(f);
                    System.out.println("Uploaded Filename: " + fileName);
                    return f;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<Book> getBooksFromFile(File file, HttpServletResponse response) throws IOException {
        try {

            Books books = (Books) Utilities.customUnMarshall(booksSchemaPath, file, response, true);
            return books.getBook();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<Book>();
    }

    private int insertBook(List<Book> books) {
        int count = 0;
        Connection con = null;
        ResultSet rs = null;
        PreparedStatement stm = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xml_bookstore", "root", "");
            String sql = "insert into books values(?,?,?,?,?,?,?,?)";
            for (int i = 0; i < books.size(); i++) {
                Book book = books.get(i);
                stm = con.prepareStatement(sql);
                stm.setString(1, book.getIsbn());
                stm.setString(2, book.getTitle());
                stm.setString(3, book.getAuthor());
                stm.setString(4, book.getCategoryName());
                stm.setFloat(5, book.getPrice().floatValue());
                stm.setString(6, book.getDesc());
                stm.setString(7, book.getPublisher());
                stm.setString(8, book.getUrl());
                if (stm.executeUpdate() > 0) {
                    count += 1;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stm != null) {
                    stm.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
        return count;
    }
}
